import { BasePage, storage } from "../../common/index";
import SearchService from "../../services/search";
export default class SearchController extends BasePage {
  constructor(data) {
    super(data);
    this._registerPage(SearchController);
    this.searchService = new SearchService();
    this.storage = storage;
    this.searchParams = {
      q: "",
      page: 1,
    };
  }
  onLoad() {
    this.init();
  }
  onShow() {
    console.log(this.storage.data.history);
    this.data.history = this.storage.data.history || [];
  }
  /**
   * 初始化方法
   */
  init() {
    const self = this;
    this._wx.getSystemInfo({
      success: function (res) {
        self.data.scrollHeight = res.windowHeight - 80;
      },
    });
  }
  /**
   * 输入框获得焦点
   */
  inputFocus() {
    this.data.isFocus = true;
  }
  /**
   * 发送请求
   */
  sendSearchHttp() {
    this.searchService.searchBook(this.searchParams).then((data) => {
      data.map((item) => {
        for (let key in item) {
          item[key] = item[key].trim();
        }
      });
      this.data.searchData = this.data.searchData.concat(data);
      this.data.isSearch = false;
      this.data.isLoadMore = false;
    });
  }
  /***
   *
   */
  addHistory(word) {
    let result = [];
    const history = this.data.history;
    const isHave = history.find((item) => item === word);
    if (isHave) {
      return;
    }
    if (history.length > 10 || history.length == 10) {
      result.push(word);
      history.map((item, index) => {
        if (index != history.length - 1) {
          result.push(item);
        }
      });
    } else {
      history.unshift(word);
    }
    if (result.length == 0) {
      result = history;
    }
    this.data.history = result;
    this.storage.data.history = result;
  }
  searchByTag(e) {
    this.data.searchText = this.searchParams.q = e.currentTarget.dataset.value;
    this.data.isSearch = true;
    this.data.searchData = [];
    this.sendSearchHttp();
  }
  /**
   * 查询小说
   */
  serachByInput() {
    this.data.searchData = [];
    if (this.searchParams.q) {
      this.addHistory(this.searchParams.q);
      this.data.isSearch = true;
      this.sendSearchHttp();
    }
  }
  /**
   * 搜索框数据改变事件
   * @param {Object} e 数据对象
   */
  changeInputText(e) {
    this.data.searchText = this.searchParams.q = e.detail.value;
  }

  /**
   * 滚动到底部
   */
  bindDownLoad() {
    this.searchParams.page += 1;
    this.data.isLoadMore = true;
    this.sendSearchHttp();
  }
}

new SearchController({
  searchText: "", // 输入内容
  searchData: [], // 查询出的书籍
  history: [],
  isSearch: false, // 是否是查询 用来显示查询动画
  isFocus: true, // 是否是输入框获得焦点 用来显示搜索历史记录
  searchHistory: [], // 查询历史数据
  scrollHeight: 0,
  isLoadMore: false,
  page: 1, //查询历史数据
});
